package cn.starrysky.hrm.service.impl;

import cn.starrysky.hrm.domain.LoginUser;
import cn.starrysky.hrm.domain.Meal;
import cn.starrysky.hrm.mapper.LoginUserMapper;
import cn.starrysky.hrm.mapper.MealMapper;
import cn.starrysky.hrm.properties.AuthDetailAdminProperties;
import cn.starrysky.hrm.properties.AuthDetailWebsiteProperties;
import cn.starrysky.hrm.service.ILoginUserService;
import cn.starrysky.hrm.util.AjaxResult;
import cn.starrysky.hrm.util.HttpUtil;
import cn.starrysky.hrm.utils.ValidUtils;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author starrysky
 * @since 2021-03-05
 */
@Service
public class LoginUserServiceImpl extends ServiceImpl<LoginUserMapper, LoginUser> implements ILoginUserService {

    @Autowired
    private LoginUserMapper loginUserMapper;
    @Value("${auth.password.tokenurl}")
    private String tokenurl;
    @Autowired
    private AuthDetailAdminProperties authDetailAdminProperties;
    @Autowired
    private AuthDetailWebsiteProperties authDetailWebsiteProperties;

    @Override
    @Transactional
    public boolean insert(LoginUser loginUser) {
        //保存loginuser 返回主键
        boolean insert = super.insert(loginUser);
        //保存meal中间表 t_user_meal
        loginUserMapper.addUserMeal(loginUser.getMealId(),loginUser.getId());
        return insert;
    }

    @Override
    public AjaxResult login(LoginUser loginUser) {
        //校验
        String username = loginUser.getUsername();
        String password = loginUser.getPassword();
        Integer type = loginUser.getType();
        ValidUtils.assertNotNull(username, "用户名不能为空");
        ValidUtils.assertNotNull(password, "密码不能为空");
        ValidUtils.assertNotNull(type, "用户类型错误,请刷新重试");
        //拼接url
        String clientid=null;
        String secret=null;
        if(type.intValue()==LoginUser.TYPE_ADMIN){ //
            //admin
            clientid=authDetailAdminProperties.getClientid();
            secret=authDetailAdminProperties.getSecret();
        }else {

            clientid=authDetailWebsiteProperties.getClientid();
            secret=authDetailWebsiteProperties.getSecret();
        }
//      client_id=%s&client_secret=%s&grant_type=password&redirect_uri=http://www.baidu.com&username=%s&password=%s"
        String url = String.format(tokenurl, clientid, secret, username, password);
        //获取token
        Map<String, String> map = HttpUtil.sendPost(url);

        //返回token
        return AjaxResult.me().setResultObj(map);
    }
}
